<?

class common {

	function multi_array_to_list($array,$key="",$quote=false) {
		$tmparray = array();

		if (!empty($key)) {
			foreach($array as $row) {
				if(!is_array($row[$key]) && array_key_exists($key, $row))
					array_push($tmparray,$row[$key]);
			}
		}
		if($quote)
  		array_walk($tmparray, create_function('&$v,$k','$v = "\'" . $v. "\'";'));

		$list = implode(",", $tmparray);

		return $list;
	}

  function getip() {
  	if (isSet($_SERVER)) {
  	if (isSet($_SERVER["HTTP_X_FORWARDED_FOR"])) {
  	$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  	} elseif (isSet($_SERVER["HTTP_CLIENT_IP"])) {
  	$realip = $_SERVER["HTTP_CLIENT_IP"];
  	} else {
  	$realip = $_SERVER["REMOTE_ADDR"];
  	}

  	} else {
  	if ( getenv( 'HTTP_X_FORWARDED_FOR' ) ) {
  	$realip = getenv( 'HTTP_X_FORWARDED_FOR' );
  	} elseif ( getenv( 'HTTP_CLIENT_IP' ) ) {
  	$realip = getenv( 'HTTP_CLIENT_IP' );
  	} else {
  	$realip = getenv( 'REMOTE_ADDR' );
  	}
  	}
  	return $realip;
	}

function confirm_username($member_id,$db){
    $sql = "SELECT member_id
            FROM members
            WHERE member_id = '$member_id'";
    $query = $db->query($sql);
    $r = $db->fetch_array($query);

    if(!$query || ($db->num_results($query)<=0))
      return 1;
    else
      return 0;
  }

function confirm_password($username,$password,$cipher,$salt,$db){
    $sql = "SELECT member_id, password
            FROM members
            WHERE username = '$username'";
    $query = $db->query($sql);
    $r = $db->fetch_array($query);

    if(count($r)>0) {
      $user_id = $r["user_id"];
      $enc_password = $r["password"];
      $dec_password = $cipher->decode($enc_password,$salt);

      if($dec_password == $password)
        return $user_id;
      else
        return "";
    }

    return "";
  }

  function confirm_permission($username,$password,$db){

	$sql = "SELECT member_id
			FROM members
			WHERE username = '$username'
			AND password = '$password'";
 	$query = $db->query($sql);
 	$r = $db->fetch_array($query);

      $member_id = $r["member_id"];

      return $member_id;
  }

  function confirm_uid($uid,$db){

	$sql = "SELECT member_id
			FROM members
			WHERE member_id = '$uid'";

 	$query = $db->query($sql);
 	$r = $db->fetch_array($query);

 	if(!$query || ($db->num_results($query)<=0))
	  return 1;
	else
      return 0;
  }


  function redirect($url){
    header("Location: ".$url);
    return true;
  }

  function validation_image() {
  	header("Content-Type: image/png");

  	$font = "/fonts/framdit.ttf";
  	$new_string = "";
  	srand((double)microtime()*1000000);
    $string = md5(rand(0,9999));
    $new_string = substr($string, 17, 5);

    session_start();
    session_register('new_string');

    $im = imagecreate(65,20);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $white = imagecolorallocate($im, 255, 255, 255);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagefill($im, 0, 0, $white);
    imagettftext($im, 13, 0, 11, 16, $grey, $font, $new_string);
    imagettftext($im, 13, 0, 10, 15, $black, $font, $new_string);
    imagepng($im);
    imagedestroy($im);

    $_SESSION['ns'] = $new_string;
  }

  function check_validation_code($validation_code) {
    $random = trim($validation_code);

    if ($_SESSION['ns'] == $validation_code)
      return true;
    else
      return false;
  }

  function sendmail($to,$from,$subject,$body) {
    $result = mail($to, $subject, $body,
                   "From: $from\r\n" .
                   "Reply-To: $from\r\n" .
                   "X-Mailer: PHP/" . phpversion());
    return $result;
  }
}

class pagination extends common {
  var $pages = 0;
  var $total_items = 0;
  var $per_page = 0;
  var $current_page_num = 0;
  var $base_url = '';
  var $max_pages_to_show = 0;

  function pagination($total_items, $per_page, $current_page_num, $base_url, $max_pages_to_show) {
      $this->pages = ceil($total_items / $per_page);
      $this->total_items = $total_items;
      $this->per_page = $per_page;
      $this->current_page_num = (!is_numeric($current_page_num) || $current_page_num > $this->pages || $current_page_num < 1) ? 1 : intval($current_page_num);
      $this->base_url = $base_url;
      $this->max_pages_to_show = $max_pages_to_show;
  }

  function display_pagination() {
    echo "Pages: ";

    if($this->current_page_num != 1) {
      $pageprev = $this->current_page_num - 1;
      echo "<a href=\"".$this->base_url."?Page=".$pageprev."\"><< Prev</a> ";
    }

    $showpages = round($this->max_pages_to_show/2);
    $numofpages = $this->pages;

    if ($numofpages > $showpages) {
      $startpage = $this->current_page_num - $showpages - 1;
    } else {
      $startpage = 0;
    }

    if ($startpage < 0){
      $startpage = 0;
    }

    if ($numofpages > $showpages) {
      $endpage = $this->current_page_num + $showpages;
    } else {
      $endpage = $showpages;
    }

    if ($endpage > $numofpages){
      $endpage = $numofpages;
    }

    for($i = $startpage; $i < $endpage; $i++) {
      $real_page = $i + 1;
      if ($real_page!=$this->current_page_num){
        echo " <a href=\"".$this->base_url."?Page=".$real_page."\">".$real_page."</a> ";
      } else {
        echo "<b>".$real_page."</b>";
      }
    }

    if(($this->total_items-($this->per_page*$this->current_page_num)) > 0){
      $pagenext = $this->current_page_num + 1;
      echo " <a href=\"".$this->base_url."?Page=".$pagenext."\">Next >></a> ";
    }
  }

  function calculate_lower_limit($per_page, $current_page_num) {
    $lower_limit = ($per_page * $current_page_num) - $per_page;
    return $lower_limit;
  }
}

class session extends common {
  var $uname;
  var $uid;
  var $time;
  var $logged_in;

  function session($common,$db) {
    $this->time = time();
    $this->start_session($common,$db);
  }

  function start_session($common,$db) {
    session_start();

    $this->logged_in = $this->check_login($common,$db);

    if(!$this->logged_in) {
      $this->uname = $_SESSION["uname"] = "guest";
    }
  }

  function login ($username,$password,$common,$db) {

    $result = $common->confirm_permission($username,$password,$db);
    if(empty($result))
       return false;

    $this->uname = $_SESSION["uname"] = $username;
    $this->uid = $_SESSION["uid"] = $result;
	$uid = $result;

    return true;
  }

  function logout() {
    unset($_SESSION["uname"]);
    unset($_SESSION["uid"]);

    $this->logged_in = false;

    $this->username = $_SESSION["uname"] = "guest";
  }

  function check_login($common,$db) {
    if(isset($_SESSION["uname"]) && isset($_SESSION["uid"]) && ($_SESSION["uname"] != "guest")) {
      if($common->confirm_username($_SESSION["uid"],$db) != 0) {
         unset($_SESSION["uname"]);
         unset($_SESSION["uid"]);
         return false;
      }
      return true;
    } else {
      return false;
    }
  }
}

class file extends common {

	function rmdir_recursive($path) {
		$dir = opendir($path) ;
		while ($entry = readdir($dir)) {
	  		if ( is_file("$path/$entry")) {
				unlink($path.$entry);
	  		} elseif (is_dir("$path/$entry") && $entry!="." && $entry!="..") {
				rmdirr("$path/$entry");
	  		}
	 	}

		closedir($dir) ;
		return rmdir($path) ;
	}

	function move_uploaded($tmp_filename, $filename) {
		return move_uploaded_file($tmp_filename, $filename);
	}

	function delete_file($filename) {
		unlink($filename);
	}

  function rmdirr($path) {
    $dir = opendir($path) ;
    while ($entry = readdir($dir)) {
      if ( is_file("$path/$entry")) {
        unlink($path.$entry);
      } elseif (is_dir("$path/$entry") && $entry!="." && $entry!="..") {
        rmdirr("$path/$entry");
      }
     }

    closedir($dir) ;
    return rmdir($path) ;
  }

  function delete($filename) {
    unlink($filename);
  }
}

